package buzzword;

import java.util.ArrayList;
import java.util.List;

import json.JSONArray;
import json.JSONException;
import json.JSONObject;

public class Board {

	private List<Field> fieldValues;
	private List<String> words;
	private int columns;
	private int rows;

	public Board() {

	}

	public String get(int gameID, String playerName, JSONObject parsedObject)
			throws JSONException {
		if (fieldValues == null)
			this.initializeBoard(parsedObject);
		words = updateDrawnWords(parsedObject.getJSONArray("drawn"));
		return parsedObject.getString("status");
	}

	public int getRows() {
		return this.rows;
	}

	public int getColumns() {
		return this.columns;
	}

	private void initializeBoard(JSONObject parsedObject) throws JSONException {
		fieldValues = parseFieldValues(parsedObject.getJSONArray("board"));
		this.checkRowsColumns();
	}

	private void checkRowsColumns() {
		Field currentField;
		for (int i = 0; i < fieldValues.size(); i++) {
			currentField = fieldValues.get(i);
			if (currentField.getColumn() > this.columns)
				this.columns = currentField.getColumn();
			if (currentField.getRow() > this.rows)
				this.rows = currentField.getRow();
		}

	}

	private List<Field> parseFieldValues(JSONArray value) throws JSONException {
		JSONObject tmp;
		List<Field> fields = new ArrayList<Field>();
		for (int i = 0; i < value.length(); i++) {
			tmp = value.getJSONObject(i);
			fields.add(new Field(tmp));
		}
		return fields;
	}

	private List<String> updateDrawnWords(JSONArray currentArray)
			throws JSONException {
		List<String> parsed = new ArrayList<String>();
		for (int i = 0; i < currentArray.length(); i++) {
			parsed.add(currentArray.getString(i));
		}
		return parsed;
	}

	public List<String> getWords() {
		return this.words;
	}

	public List<Field> getFields() {
		return this.fieldValues;
	}

}
